﻿using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using GBlog.Core.Entities;

namespace GBlog.Core.Attributes
{
    public class RequireLoginAttribute : ActionFilterAttribute
    {
        public string Role = null;
        public RequireLoginAttribute() { }
        public RequireLoginAttribute(string Role) { this.Role = Role; }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            ViewResult viewResult = filterContext.Result as ViewResult;
            User user = HttpContext.Current.User as User;
            if (user == null)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "Login" }, { "controller", "Login" }});
            }
            else if (!string.IsNullOrEmpty(Role) && !user.IsInRole(Role))
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "Index" }, { "controller", "Home" } });
            }
        }
    }
}